﻿using Microsoft.Extensions.Caching.Memory;
using System;

namespace Batman.Cache.Providers
{
    public class MemoryCachingProvider : ICachingProvider
    {
        private IMemoryCache _cache;

        public MemoryCachingProvider(IMemoryCache cache)
        {
            _cache = cache;
        }

        public object Get(string cacheKey)
        {
            return _cache.Get(cacheKey);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="factory">如果缓存为null，则执行该委托方法，并把结果写入缓存</param>
        /// <param name="absoluteExpirationRelativeToNow">默认是30秒缓存</param>
        /// <returns></returns>
        public object Get(string cacheKey, Func<object> factory, TimeSpan? absoluteExpirationRelativeToNow = null)
        {
            var cacheValue = _cache.Get(cacheKey);

            if (cacheValue == null) cacheValue = factory();
            if (cacheValue != null)
            {
                absoluteExpirationRelativeToNow = absoluteExpirationRelativeToNow.HasValue ? absoluteExpirationRelativeToNow : TimeSpan.FromSeconds(30);
                _cache.Set(cacheKey, cacheValue, absoluteExpirationRelativeToNow.Value);
            }

            return cacheValue;
        }

        public void Set(string cacheKey, object cacheValue, TimeSpan absoluteExpirationRelativeToNow)
        {
            _cache.Set(cacheKey, cacheValue, absoluteExpirationRelativeToNow);
        }

        /// <summary>
        /// 移除指定缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        public void Remove(string cacheKey)
        {
            _cache.Remove(cacheKey);
        }

    }
}
